import classNames from "classnames";
import React, { useEffect, useRef, createRef, useState } from "react";
import { AtSearchBar, AtInput } from "taro-ui";
import "./index.scss";

interface Props {
  value: string;
  onInput: (value) => void;
  className?: string;
}
export const SearchBar = ({ value, onInput, className }: Props) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const [isFocus, setIsFocus] = useState(false);
  return (
    <div
      className={classNames("search-bar", className, {
        "has-focus": isFocus,
      })}
    >
      <input
        value={value}
        autoComplete="off"
        aria-autocomplete="off"
        id="searchInput"
        className="search-input"
        ref={inputRef}
        type="text"
        placeholder="搜索"
        onFocus={() => {
          setIsFocus(true);
        }}
        onBlur={() => {
          setTimeout(() => {
            setIsFocus(false);
          }, 0);
        }}
        onChange={(e) => {
          onInput(e.target.value);
        }}
      />
      <span className="iconfont icon-search-2-line search-icon"></span>
      {(isFocus || value) && (
        <label htmlFor="searchInput">
          <span
            className="iconfont icon-error close-icon"
            onClick={() => {
              setTimeout(() => {
                setIsFocus(false);
                onInput("");
              }, 1);
            }}
          ></span>
        </label>
      )}
      {(isFocus || value) && (
        <span
          className="cancel"
          onClick={() => {
            onInput("");
            setIsFocus(false);
          }}
        >
          取消
        </span>
      )}
    </div>
  );
};
